package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public ResultInfo login(String username, String password) {
        //根据username进行查询
        Employee employee = employeeMapper.findByUsername(username);
        if (employee == null){
            return ResultInfo.error("当前用户不存在");
        }
        //2.如果有用户，对password进行比对
        //先进行加密
        String passwordMd5 = SecureUtil.md5(password);
        if (!StringUtils.equals(passwordMd5,employee.getPassword())){
            return ResultInfo.error("密码错误");
        }
        //3.
        if (employee.getStatus() == employee.STATUS_DISABLE){
            return ResultInfo.error("账户已被封");
        }

        //4.登陆成功，返回employee信息
        return ResultInfo.success(employee);
        }
    @Override
    public List<Employee> findByName(String name) {
        return employeeMapper.findByName(name);
    }
    //保存员工
    @Override
    public void save(Employee employee){
        //1.将参数补齐
        long id = IdUtil.getSnowflake(1,1).nextId();
        employee.setId(id);//将long方法的参数名id传进去作为主键
        employee.setPassword(SecureUtil.md5("111"));//设置默认密码
        employee.setStatus(Employee.STATUS_ENABLE);//设置状态为1

        //todo
        //时间
//        employee.setCreateTime(new Date());
//        employee.setUpdateTime(new Date());

        //todo
//        //用户
//        employee.setCreateUser(1l);
//        employee.setUpdateUser(1L);

        employeeMapper.save(employee);
    }
    //3.查询员工
    public Employee findById(Long id){
        return employeeMapper.findById(id);
    }
    //4.修改员工
    public void update(Employee employee){
        //todo
//        employee.setUpdateUser(1L);//设置参数
//        employee.setUpdateTime(new Date());
        //更新
        employeeMapper.update(employee);
    }
}
